package service.impl;

import dao.IMovieDao;
import dao.impl.MovieDaoImpl;
import entity.Movie;

import java.util.ArrayList;
import java.util.List;

public class MovieServiceImpl implements service.IMovieService {
    private final IMovieDao movieDao = new MovieDaoImpl();
    private List<Movie> movies;

    public MovieServiceImpl() {
        movies = movieDao.load();
    }

    @Override
    public List<Movie> findAll() {
        return movies;
    }

    @Override
    public boolean add(Movie movie) {
        // 检查影片ID是否已存在
        if (movies.stream().anyMatch(m -> m.getId().equals(movie.getId()))) {
            System.out.println("影片ID已存在，请使用其他ID！");
            return false;
        }
        movies.add(movie);
        movieDao.save(movies);
        System.out.println("影片添加成功！");
        return true;
    }

    @Override
    public boolean delete(String id) {
        boolean result = movies.removeIf(m -> m.getId().equals(id));
        if (result) {
            movieDao.save(movies);
            System.out.println("删除成功！");
        } else {
            System.out.println("未找到影片或影片正在排片！");
        }
        return result;
    }

    @Override
    public List<Movie> searchByKeyword(String keyword) {
        return movies.stream()
                .filter(m -> m.getName().contains(keyword) || m.getDirector().contains(keyword) || m.getActors().contains(keyword))
                .toList();
    }

    @Override
    public void shutdown() {
        movieDao.save(movies);
    }
}